﻿using System;
using System.Data;

namespace zijian666.Data
{
    /// <summary>
    /// 自动关闭的 <see cref="IDbCommand"/> 结构
    /// </summary>
    public readonly struct SelfClosingDbCommand : IDisposable
    {
        private readonly IDbConnection _connection;
        private readonly IDbCommand _command;

        public SelfClosingDbCommand(IDbConnection connection)
        {
            if (connection is null)
            {
                throw new ArgumentNullException(nameof(connection));
            }

            _connection = connection.OpenIfClosed() ? connection : null;
            _command = null;
        }

        public SelfClosingDbCommand(IDbCommand command)
        {
            _command = command ?? throw new ArgumentNullException(nameof(command));
            _connection = command.Connection.OpenIfClosed() ? command.Connection : null;
        }

        public void Dispose()
        {
            _command?.Dispose();
            _connection?.SafeClose();
        }
    }
}
